package com.qdlc.p2p.biz.web.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.qdlc.p2p.biz.util.HclientFileUtil;
import com.qdlc.p2p.biz.util.UserLoginUtil;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.UserType;
import com.qdlc.p2p.common.enums.EnumUploadImgType;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.ImageUtil;
import com.qdlc.p2p.common.util.RSAUtil;
import com.qdlc.p2p.common.util.ReflectUtil;
import com.qdlc.p2p.common.util.UploadFileUtil;
import com.qdlc.p2p.common.web.action.CommonAction;
import com.qdlc.p2p.dal.checkrule.RsaFormEncryptRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.util.UserUtils;

public class BaseAction<T> extends CommonAction {

	@SuppressWarnings("unchecked")
	protected Class<T> entityClass = ReflectUtil.getSuperClassGenricType(getClass());
	
	private final static Logger logger=Logger.getLogger(BaseAction.class);

	protected T model;
	protected String searchName;
	private File file;
	private String fileFileName;
	private String fileContentType;
	private File[] files;
	private String[] filesFileName;

	/**
	 * 实现ModelDriven接口getModel方法供子类继承
	 * 
	 * @return T 对象实例
	 */
	public T getModel() {
		try {
			model = entityClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return model;
	}

	/**
	 * 上传图片
	 * @return 图片路径
	 * @throws IOException if has error
	 */
	protected String imgUpload(String type) throws IOException {
		String picPath = null;
		if (file != null) {
			if (!EnumUploadImgType.PAY.getValue().equals(type) && !ImageUtil.fileIsImage(file)) {
				throw new BusinessException("您上传的图片无效，请重新上传！", BusinessException.TYPE_JSON);
			} else {
				picPath = HclientFileUtil.uploadFileMethod(UploadFileUtil.getMessage(type+"Url"), UploadFileUtil.getMessage(type+"Nid"), file);
				/*Date d = DateUtil.getNow();
				String upfiesDir = ServletActionContext.getServletContext().getRealPath("/data/upfiles/images/");
				String realPath = ServletActionContext.getServletContext().getRealPath("");
				String destFileName = upfiesDir + DateUtil.dateStr2(d) + "/"  
						+ entityClass.getSimpleName() + "/" + UUID.randomUUID()
						+ fileFileName.substring(fileFileName.lastIndexOf("."));
				File imageFile = new File(destFileName);
				FileUtils.copyFile(file, imageFile);
				picPath = destFileName.replace(realPath, "").replace(File.separator, "/");*/
			}
		}
		return picPath;
	}

	/**
	 * 上传图片
	 * @return 图片路径
	 * @throws IOException if has error
	 */
	protected String imgUploadToWeb(String type,String mfileName) throws IOException {
		return imgUploadToWeb(type,mfileName,null);
	}

	/**
	 * 上传图片
	 * @return 图片路径
	 * @throws IOException if has error
	 */
	protected String imgUploadToWeb(String type,String mfileName,String webUrl) throws IOException {
		String picPath = null;
		if (file != null) {
			if (!EnumUploadImgType.PAY.getValue().equals(type) && !ImageUtil.fileIsImage(file)) {
				throw new BusinessException("您上传的图片无效，请重新上传！", BusinessException.TYPE_JSON);
			} else {
				picPath = HclientFileUtil.uploadFileMethodToWeb(UploadFileUtil.getMessage(type+"Url"), UploadFileUtil.getMessage(type+"Nid"), file, mfileName,webUrl);
				/*Date d = DateUtil.getNow();
				String upfiesDir = ServletActionContext.getServletContext().getRealPath("/data/upfiles/images/");
				String realPath = ServletActionContext.getServletContext().getRealPath("");
				String destFileName = upfiesDir + DateUtil.dateStr2(d) + "/"
						+ entityClass.getSimpleName() + "/" + UUID.randomUUID()
						+ fileFileName.substring(fileFileName.lastIndexOf("."));
				File imageFile = new File(destFileName);
				FileUtils.copyFile(file, imageFile);
				picPath = destFileName.replace(realPath, "").replace(File.separator, "/");*/
			}
		}
		return picPath;
	}
	
	/**
	 * 上传多图片
	 * @return 图片路径数组
	 * @throws IOException if has error
	 */
	protected String[] imgsUpload() throws IOException {
        String fileIndex = paramString("fileIndex");
        int fileSize = paramInt("fileSize");
        String[] indexs = fileIndex.split(",");
		String[] picPath = new String[fileSize];
		if (files != null && files[0] != null) {
			for (int i = 0; i < files.length; i++) {
				if (!ImageUtil.fileIsImage(files[i])) {
					printResult("您上传的图片无效，请重新上传！", true);
				} else {
				    int index = Integer.parseInt(indexs[i]);
					Operator oper = getOperator();
					Date d = DateUtil.getNow();
					String upfiesDir = ServletActionContext.getServletContext().getRealPath("/data/upfiles/images/");
					String realPath = ServletActionContext.getServletContext().getRealPath("");
					String destFileName = upfiesDir + DateUtil.dateStr2(d) + "/" + oper.getId()
							+ entityClass.getSimpleName() + "/" + DateUtil.dateStr(d, "HHmmss") + i
							+ filesFileName[i].substring(filesFileName[i].lastIndexOf("."));
					File imageFile = new File(destFileName);
					FileUtils.copyFile(files[i], imageFile);
					picPath[index] = destFileName.replace(realPath, "").replace(File.separator, "/");
				}
			}
		}
		return picPath;
	}
	/**
	 * 获取Session中的用户对象
	 * 
	 * @return
	 */
	public User getSessionUser() {
		User user = UserLoginUtil.getLoginUser();
		return user;
	}

	/**
	 * 获取Session中的用户对象的ID
	 * 
	 * @return
	 */
	protected long getSessionUserId() {
		User user = getSessionUser();
		return user.getUserId();
	}

	/**
	 * 获取Session中的用户对象
	 * 
	 * @return
	 */
	protected String getSessionUserName() {
		User user = getSessionUser();
		return user.getUserName();
	}

	/**
	 * 封装获取Session中的用户对象
	 * 
	 * @return
	 */
	protected Operator getOperator() {
		return (Operator) session.get(Constant.SESSION_OPERATOR);
	}

	/**
	 * 封装获取Session中的用户对象的用户名
	 * 
	 * @return
	 */
	protected String getOperatorUserName() {
		Operator operator = (Operator) session.get(Constant.SESSION_OPERATOR);
		return operator.getUserName();
	}

	/**
	 * 封装获取Session中的用户对象的ID
	 * 
	 * @return
	 */
	protected long getOperatorId() {
		Operator operator = (Operator) session.get(Constant.SESSION_OPERATOR);
		if (operator == null)
			return 49l;
		return operator.getId();
	}

	public boolean isSession() {
		User sessionUser = this.getSessionUser();
		if (sessionUser == null)
			return false;
		return true;
	}

	/**
	 * 重定向
	 * 
	 * @param url
	 */
	protected void redirect(String url) {
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 前台重定向
	 * 
	 * @param url
	 */
	protected void frontRedirect(String url) {
		try {
			response.sendRedirect(SystemConfigHelper.getValue(Nid.WEB_URL) + url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * RSA 公钥的Modulus与PublicExponent的hex编码形式
	 * 
	 * @throws Exception
	 */
	protected void initRSAME() throws Exception {
		RsaFormEncryptRuleCheck rsaFormEncrypt = RuleCheckHelper.getValue(RsaFormEncryptRuleCheck.class);
		if (rsaFormEncrypt.enable_formEncrypt) {
			RSAPublicKey rsap;
			rsap = (RSAPublicKey) RSAUtil.getKeyPair().getPublic();
			String module = rsap.getModulus().toString(16);
			String empoent = rsap.getPublicExponent().toString(16);
			request.setAttribute("m", module);
			request.setAttribute("e", empoent);
		}
		request.setAttribute("rsaFormEncrypt", rsaFormEncrypt);
	}

	/**
	 * 回调参数拼接共用方法
	 * 
	 * @return
	 */
	public String getRequestParams() {
		String params = "";
		try {
			@SuppressWarnings("rawtypes")
			Enumeration e = (Enumeration) request.getParameterNames();
			while (e.hasMoreElements()) {
				String parName = (String) e.nextElement();
				String value = request.getParameter(parName);
				params += parName + "=" + value + "&";
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return params;
	}	
	
	/**
	 * 文件下载
	 * @param inFile
	 * @param downloadFile
	 * @throws IOException
	 */
	public void generateDownloadFile(String inFile, String downloadFile) throws IOException {
		InputStream ins = new BufferedInputStream(new FileInputStream(inFile));
		byte[] buffer = new byte[ins.available()];
		ins.read(buffer);
		ins.close();
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		response.reset();
		String userAgent = request.getHeader("User-Agent");
		if(userAgent.contains("Firefox")){
			byte[] bytes = downloadFile.getBytes();
			String filename = new String(bytes,"ISO-8859-1");
			response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
		}else{
			response.addHeader("Content-Disposition", "attachment;filename=" +java.net.URLEncoder.encode(new String(downloadFile.getBytes()), "UTF-8") );
		}

		response.addHeader("Content-Length", "" + new File(inFile).length());
		OutputStream ous = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/octet-stream");
		ous.write(buffer);
		ous.flush();
		ous.close();
	}
	/**
	 * 校验是否是投资人，如果不是，那么就跳转到借款人账户主页
	 * @throws IOException
	 */
	public void checkInvestUser() throws IOException{
		User user = getSessionUser();
		UserCache userCache = UserUtils.getUserCacheByUserId(user.getUserId());
		if(userCache == null || userCache.getUserType() == UserType.BORROWER){
			response.sendRedirect("/member/main.html");
		}
	}
	
	/**
	 * 校验是否是借款人，如果不是，那么就跳转到投资人账户主页
	 * @throws IOException
	 */
	public void checkBorrowUser() throws IOException{
		User user = getSessionUser();
		UserCache userCache = UserUtils.getUserCacheByUserId(user.getUserId());
		if(userCache == null || userCache.getUserType() == 1){
			response.sendRedirect("/member/main.html");
		}
	}
	
	
	public String getSearchName() {
		return searchName;
	}

	public void setSearchName(String searchName) {
		this.searchName = searchName;
	}
	public File[] getFiles() {
		return files;
	}
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	public void setFiles(File[] files) {
		this.files = files;
	}

	public String[] getFilesFileName() {
		return filesFileName;
	}

	public void setFilesFileName(String[] filesFileName) {
		this.filesFileName = filesFileName;
	}
}
